package com.simon.hse.activity.danger;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.CommonInput;
import com.simon.hse.http.entity.DangerEliminateListBean;
import com.simon.hse.http.entity.DangerEliminateOutput;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.http.entity.PlanCheckGetList;
import com.simon.hse.http.entity.TrainPersonOutput;
import com.simon.hse.interfaces.PopListener;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;

/**
 * 隐患排查任务
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_danger_eliminate)
public class DangerEliminateActivity extends BaseActivity implements PopListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_more)
    LinearLayout mLl_more;

    @ViewInject(R.id.ll_danger_eliminate_company)
    LinearLayout mLl_danger_eliminate_company;

    @ViewInject(R.id.tv_danger_eliminate_company)
    TextView mTv_danger_eliminate_company;

    @ViewInject(R.id.ll_danger_eliminate_more_rate)
    LinearLayout mLl_danger_eliminate_more_rate;

    @ViewInject(R.id.tv_danger_eliminate_more_rate)
    TextView mTv_danger_eliminate_more_rate;

    @ViewInject(R.id.ll_danger_eliminate_more_station)
    LinearLayout mLl_danger_eliminate_more_station;

    @ViewInject(R.id.tv_danger_eliminate_more_station)
    TextView mTv_danger_eliminate_more_station;

    @ViewInject(R.id.ll_danger_eliminate_more_standard)
    LinearLayout mLl_danger_eliminate_more_standard;

    @ViewInject(R.id.tv_danger_eliminate_more_standard)
    TextView mTv_danger_eliminate_more_standard;

    @ViewInject(R.id.tv_function_1)
    TextView mTv_factory;

    @ViewInject(R.id.ll_function_1)
    LinearLayout mLl_factory;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;


    @ViewInject(R.id.ll_StartTime)
    LinearLayout mLlStartTime;

    @ViewInject(R.id.ll_EndTime)
    LinearLayout mLlEndTime;

    @ViewInject(R.id.tv_StartTime)
    TextView tvStartTime;

    @ViewInject(R.id.tv_EndTime)
    TextView tvEndTime;

    @ViewInject(R.id.iv_common_right)
    ImageView ivAdd;
    @ViewInject(R.id.iv_common_right)
    ImageView mIv_common_right;

    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<DangerEliminateOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();// 隐患排查任务列表
    private List<TrainPersonOutput.DataBean.PageDataBean> mListTrainPerson = new ArrayList<>();// 培训人
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerDepartList = new ArrayList<>();// 部门
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerAreasList = new ArrayList<>();// 区域
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerRatesList = new ArrayList<>();// 频率
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerStationsList = new ArrayList<>();// 岗位
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mDangerStandardsList = new ArrayList<>();// 标准类型
    private boolean isShowMore = false;
    private String personInCharge;// 隐患负责人
    private String factory;//工厂ID
    private String unit;//排查单位

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("隐患排查任务");
        mIv_common_right.setImageResource(R.mipmap.tab_add_icon);

        initRecyclerView();
        initData();
        initPopData();
    }

    @Event(value = {R.id.iv_common_left, R.id.ll_eliminate_more, R.id.ll_danger_eliminate_company, R.id.ll_danger_eliminate_more_rate, R.id.ll_function_1,R.id.iv_common_right})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.ll_eliminate_more:
                if (isShowMore) {
                    mLl_more.setVisibility(View.GONE);
                } else {
                    mLl_more.setVisibility(View.VISIBLE);
                }
                isShowMore = !isShowMore;
                break;
            case R.id.ll_danger_eliminate_company:
                initCommonPop(mLl_danger_eliminate_company, mTv_danger_eliminate_company, mDangerDepartList, 2);
                break;
            case R.id.ll_danger_eliminate_more_rate:
                initPersonPop(mLl_danger_eliminate_more_rate, mTv_danger_eliminate_more_rate);
                break;
            case R.id.ll_function_1:
                initCommonPop(mLl_factory, mTv_factory, MyApplication.getInstance().mFactoryList, 1);
                break;
            case R.id.iv_common_right:
                startActivityForResult(new Intent(this, AddTaskActivity.class), 1);
                break;
        }
    }

    @Event(value = { R.id.ll_danger_eliminate_more_standard
            , R.id.tv_more_confirm, R.id.tv_more_reset, R.id.ll_StartTime, R.id.ll_EndTime})
    private void more(View view) {
        switch (view.getId()) {

            case R.id.ll_danger_eliminate_more_standard:
//                initCommonPop(mLl_danger_eliminate_more_standard, mTv_danger_eliminate_more_standard, mDangerStandardsList);
                initPersonPop(mLl_danger_eliminate_more_standard, mTv_danger_eliminate_more_standard);
                break;
            case R.id.tv_more_confirm:
                mLl_more.setVisibility(View.GONE);
                isShowMore = !isShowMore;
                initData();
                break;
            case R.id.tv_more_reset:
                mTv_danger_eliminate_more_rate.setText("");
                mTv_danger_eliminate_more_rate.setHint("请选择");
                tvStartTime.setText("");
                tvStartTime.setHint("请选择");
                tvEndTime.setText("");
                tvEndTime.setHint("请选择");
                personInCharge = "";

                break;
            case R.id.ll_StartTime:
                reportDate(tvStartTime);
                break;
            case R.id.ll_EndTime:
                reportDate(tvEndTime);
                break;
        }
    }

    private void initRecyclerView() {
        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage * 10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(DangerEliminateActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(DangerEliminateActivity.this, R.layout.layout_item_dagner_eliminate, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DangerEliminateOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DangerEliminateOutput.DataBean.PageDataBean dataBean) {
                TextView tv_danger_eliminate_title = holder.getView(R.id.tv_danger_eliminate_title);
                TextView tv_danger_eliminate_state = holder.getView(R.id.tv_danger_eliminate_state);
                TextView tv_danger_eliminate_person = holder.getView(R.id.tv_danger_eliminate_person);
                TextView tv_danger_eliminate_date = holder.getView(R.id.tv_danger_eliminate_date);

                tv_danger_eliminate_title.setText(dataBean.getObjective());
                switch (dataBean.getPlanState()) {// (0未开始 1进行中 2已完成)
                    case "0":
                        tv_danger_eliminate_state.setText("未开始");
                        tv_danger_eliminate_state.setBackgroundResource(R.drawable.rect_dark_corner_5);
                        break;
                    case "1":
                        tv_danger_eliminate_state.setText("进行中");
                        tv_danger_eliminate_state.setBackgroundResource(R.drawable.rect_green_light_corner_5);
                        break;
                    case "2":
                        tv_danger_eliminate_state.setText("已完成");
                        tv_danger_eliminate_state.setBackgroundResource(R.drawable.rect_dark_corner_5);
                        break;
                }
                tv_danger_eliminate_person.setText("负责人：" + dataBean.getPersonInChargeText());
                String beginTime = dataBean.getBeginTime();
                if (!TextUtils.isEmpty(beginTime)) {
                    String[] split = beginTime.split(" ");
                    beginTime = split[0];
                }
                tv_danger_eliminate_date.setText("任务开始时间：" + beginTime);

            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                if (!isShowMore) {
                    Intent intent = new Intent(DangerEliminateActivity.this, DangerAreaTaskActivity.class);
//                    Bundle bundle = new Bundle();
//                    DangerEliminateOutput.DataBean.PageDataBean pageDataBean = mDataBeanList.get(position);
//                    bundle.putSerializable("SECOND_LEVEL", pageDataBean);
//                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    private void initData() {

        PlanCheckGetList planCheckGetList = new PlanCheckGetList();
        PlanCheckGetList.ModelBean modelBean = new PlanCheckGetList.ModelBean();

        modelBean.setCreateFactory(factory);
        modelBean.setUnit(unit);
        modelBean.setPersonInCharge(personInCharge);
        modelBean.setBeginTime(tvStartTime.getText().toString());
        modelBean.setEndTime(tvEndTime.getText().toString());

        planCheckGetList.setModel(modelBean);
        planCheckGetList.setLimit(10);
        planCheckGetList.setOffset(10 * (currentPage - 1));


        Call<String> call = HttpManager.getInstance().requestService().DANGER_ELIMINATE_LIST(HttpManager.getInstance().requestBody(planCheckGetList));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                DangerEliminateOutput dangerEliminateOutput = new Gson().fromJson(result, DangerEliminateOutput.class);
                if (dangerEliminateOutput.getResult().equals("Success")) {
                    totalPage = dangerEliminateOutput.getData().getRowCount();
                    List<DangerEliminateOutput.DataBean.PageDataBean> dataBeanList = dangerEliminateOutput.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(dangerEliminateOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * pop data
     */
    private void initPopData() {
        DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = new DropDownOutput.DataBean.DataDicListBean.ValueBean();
        valueBean.setKey("");
        valueBean.setValue("全部");

        mDangerDepartList.add(valueBean);
        mDangerDepartList.addAll(MyApplication.getInstance().mDangerDepartList);
        mDangerAreasList.add(valueBean);
        mDangerAreasList.addAll(MyApplication.getInstance().mDangerAreasList);
        mDangerRatesList.add(valueBean);
        mDangerRatesList.addAll(MyApplication.getInstance().mDangerRatesList);
        mDangerStationsList.add(valueBean);
        mDangerStationsList.addAll(MyApplication.getInstance().mDangerStationsList);
        mDangerStandardsList.add(valueBean);
        mDangerStandardsList.addAll(MyApplication.getInstance().mDangerStandardsList);

        TrainPersonOutput.DataBean.PageDataBean pageDataBean = new TrainPersonOutput.DataBean.PageDataBean();
        pageDataBean.setId("");
        pageDataBean.setName("全部");
        mListTrainPerson.add(pageDataBean);
        mListTrainPerson.addAll(MyApplication.getInstance().mListTrainPerson);
    }

    /**
     * 共用Pop
     */
    private void initCommonPop(LinearLayout mLl, final TextView mTv, final List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mList,final int index) {
        View inflate = LayoutInflater.from(DangerEliminateActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerEliminateActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerEliminateActivity.this, R.layout.layout_item_common_more_department, mList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {

                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mList.get(position);
                mTv.setText(valueBean.getValue());
                switch (index) {
                    case 1:
                        factory = valueBean.getKey();
                        break;
                    case 2:
                        unit = valueBean.getKey();
                        break;

                }
                factory = valueBean.getKey();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerEliminateActivity.this, inflate, mLl);
    }

    /**
     * 负责人-Pop
     * @param mLl_danger_eliminate_more_rate
     * @param mTv_danger_eliminate_more_rate
     */
    private void initPersonPop(LinearLayout ll, TextView tv) {
        View inflate = LayoutInflater.from(DangerEliminateActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerEliminateActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerEliminateActivity.this, R.layout.layout_item_common_more_department, mListTrainPerson);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<TrainPersonOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, TrainPersonOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                TrainPersonOutput.DataBean.PageDataBean pageDataBean = mListTrainPerson.get(position);
                tv.setText(pageDataBean.getName());
                personInCharge = pageDataBean.getId();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerEliminateActivity.this, inflate, ll);
    }

    /**
     * 公用时间选择
     */
    public void reportDate(TextView tv) {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(1949, 1, 1);
        String currentYMD = DateTimeUtils.getCurrentYMD();
        String[] split = currentYMD.split("-");
        selectedDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        endDate.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");//设置日期格式
                tv.setText(sdf_ymd.format(date));
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        pvTime.show();
    }

    @Override
    public void upData() {
        currentPage = 1;
        mDataBeanList.clear();
        initData();
    }
}
